package com.easy.common.util;
//找回密码时验证用

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

//用于生成和验证邮箱验证码
public class VerificationCodeUtil {
    // 存储邮箱验证码，key为邮箱，value为验证码和过期时间
    private static final Map<String, CodeInfo> codeMap = new ConcurrentHashMap<>();
    // 验证码有效期（5分钟）
    private static final long EXPIRE_TIME = 5 * 60 * 1000;
    //生成4位数字验证码
    public static String generateCode() {
        Random random = new Random();
        int code = 1000 + random.nextInt(9000); // 1000-9999
        return String.valueOf(code);
    }
    //保存验证码到内存，并设置过期时间
    public static void saveCode(String email, String code) {
        codeMap.put(email, new CodeInfo(code, System.currentTimeMillis() + EXPIRE_TIME));
    }
    //验证验证码是否正确且未过期
    public static boolean verifyCode(String email, String code) {
        CodeInfo codeInfo = codeMap.get(email);
        if (codeInfo == null) {
            return false;
        }
        // 检查验证码是否过期
        if (System.currentTimeMillis() > codeInfo.expireTime) {
            codeMap.remove(email); // 过期则删除
            return false;
        }
        // 验证用户输入的验证码与存储的验证码是否一致
        boolean result = codeInfo.code.equals(code);

        // 验证成功后删除验证码
        if (result) {
            codeMap.remove(email);
        }

        return result;
    }
    //删除指定邮箱的验证码
    public static void removeCode(String email) {
        codeMap.remove(email);
    }
    //验证码信息内部类，用于存储验证码及其过期时间
    private static class CodeInfo {
        private final String code;
        private final long expireTime;

        public CodeInfo(String code, long expireTime) {
            this.code = code;
            this.expireTime = expireTime;
        }
    }
}
